from django.conf import settings
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.utils import merge_cookie_cart_to_redis
from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.serializers import QQAuthCallBackSerializer, UserCenterInfoSerializer
from oauth.utils import OAuthQQ


# 认证类
# from rest_framework.authentication import i

#  url(r'^qq/authorization/?next=....$', views.QQAuthURLView.as_view()),
class OauthQQView(APIView):
    def get(self, request):
        # 获取参数,登陆成功跳转的url
        next_url = request.query_params.get('next', '/')

        # 组织QQ登陆url并返回
        # 使用工具中封装的
        oauth = OAuthQQ(state=next_url)
        login_url = oauth.get_login_url()

        return Response({'login_url': login_url})


# GET /oauth/qq/user/?code=....
class QQAuthCallBackView(CreateAPIView):
    serializer_class = QQAuthCallBackSerializer
    """
    1.获取code并校验
    2.获取open_id
        2.1 根据code获取access_token
        2.2 根据access_token获取open_id
    3,根据open_id进行处理
        3.1 如果用户绑定过,生成JWTtoken并返回
        3.2 没有绑定过,将open_id加密并返回
    """
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        # user1 = request.user

        user = self.user  # 序列化器中添加了user
        # 调用合并购物车的函数
        merge_cookie_cart_to_redis(request, user)
        response.delete_cookie('cart')
        return response



    # def post(self, request):
    #     # 接收数据,校验数据
    #     # 保存QQ登陆用户数据
    #
    #     # serializer = QQAuthCallBackSerializer(data=request.data)
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     # 返回响应,生成JWTToken
    #     return Response(serializer.data)

    def get(self, request):

        # 1. 获取code并校验
        code = request.query_params.get('code')

        if code is None:
            return Response({'message': '缺少code参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 获取open_id
        # 2.1 根据code获取access_token
        oauth = OAuthQQ()
        try:
            access_token = oauth.get_access_token(code)

            # 2.2 根据access_token获取open_id
            openid = oauth.get_openid(access_token)

        except QQAPIError:
            return Response({'message': 'QQ登录异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 3 根据open_id进行处理
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 3.2 没有绑定过, 将open_id加密并返回
            token = OAuthQQ.generate_save_user_token(openid=openid)
            return Response({'access_token': token})
        else:
            # 3.1    如果用户绑定过, 生成JWTtoken并返回
            # 由服务器生成一个jwt token，保存用户的身份信息
            user = qq_user.user
            from rest_framework_jwt.settings import api_settings

            # 生成载荷
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            # 生成jwt token
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            res_data = {
                'user_id': user.id,
                'username': user.username,
                'token': token
            }
            # 调用合并购物车函数
            merge_cookie_cart_to_redis(request, user)
            # 清除cookie
            response = Response(res_data)
            response.delete_cookie('cart')
            return response
